const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    role: 1,
    roleName: "交易市场"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.userInfo) {
      let role = app.globalData.userInfo.role;
      let roleName = app.globalData.userInfo.roleName;
      this.setData({
        role,
        roleName
      });
    }
  },

  // 切换身份
  onChange(e) {
    let role = e.currentTarget.dataset.role;
    let name = e.currentTarget.dataset.name;
    this.getMarketUserMyInfo().then((markets) => {
			let flag = false;
      if (markets && markets.length) {
        markets.forEach((item) => {
          if (item.marketRoles) {
            let Index = item.marketRoles.findIndex((r) => r.marketRoleId == role);
            // 如果没找到一样的角色就切不过去
            if (Index === -1) {
              flag = true;
            }
          }
        });
        if (flag) {
          wx.showToast({
            icon: "none",
            title: "该账号未注册其他角色"
          });
          return false;
        }
        this.changeUserInfo(role, name);
      } else {
        wx.clearStorage({
          success: () => {
            let app = getApp();
            app.globalData = {};
            wx.showToast({
              icon: "none",
              title: "该账号无登录权限"
            });
          }
        });
      }
    });
  },

  // 查看我的全部交易市场用户详细信息
  getMarketUserMyInfo() {
    return new Promise((resolve, reject) => {
      wx.$apis
        .getMyUserInfo()
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  changeUserInfo(role, name) {
    let userInfo = wx.getStorageSync("userInfo");
    userInfo = (userInfo && JSON.parse(userInfo)) || null;
    userInfo.role = role;
    userInfo.roleName = name;
    wx.setStorageSync("userInfo", JSON.stringify(userInfo));
    app.globalData.userInfo = userInfo;
    wx.showToast({
      title: "切换成功"
    }).then((res) => {
      setTimeout(() => {
        wx.reLaunch({
          url: "/pages/login/index?role=" + role
        });
      }, 300);
    });
  }
});
